package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * ClassName  JwtUtils
 * Author  XiaojianOne
 * Date  2025/3/3 15:01
 * Version  8.0
 */

public class JwtUtil {


    //过期时间 一个小时
    private static long tokenExpiration = 3600000;

    //密钥
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * 生成token
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).
                claim("username", username).
                signWith(tokenSignKey).
                compact();
        return token;
    }


    /**
     * 校验token是否有效 / 合法
     * @param token
     */
    public static Claims parseToken(String token){

        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try{

            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();

            //解析 JWT 的 Header 和 Payload，并验证其签名是否有效。
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);

            return claimsJws.getBody();

        }catch (ExpiredJwtException e){

            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){

            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }


    /**
     * 测试
     * @param args
     */
    public static void main (String[]args){

        System.out.println(JwtUtil.createToken(8L, "18363589958"));
    }
}

